package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.service.DepositService;
import com.powerbank.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;

/**
 * 押金管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/deposit")
public class DepositController {

    @Autowired
    private DepositService depositService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 计算用户押金金额
     */
    @GetMapping("/calculate")
    public Result<BigDecimal> calculateDepositAmount(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            BigDecimal depositAmount = depositService.calculateDepositAmount(userId);
            return Result.success("押金金额计算成功", depositAmount);
        } catch (Exception e) {
            log.error("计算押金金额失败：{}", e.getMessage(), e);
            return Result.error("计算押金金额失败：" + e.getMessage());
        }
    }

    /**
     * 检查是否需要支付押金
     */
    @GetMapping("/need-pay")
    public Result<Boolean> needPayDeposit(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean needPay = depositService.needPayDeposit(userId);
            return Result.success("检查完成", needPay);
        } catch (Exception e) {
            log.error("检查押金需求失败：{}", e.getMessage(), e);
            return Result.error("检查押金需求失败：" + e.getMessage());
        }
    }

    /**
     * 创建押金支付订单
     */
    @PostMapping("/create-payment")
    public Result<PaymentResultVO> createDepositPayment(@RequestParam @NotNull(message = "订单ID不能为空") Long orderId,
                                                        @RequestParam @NotBlank(message = "支付方式不能为空") String paymentMethod,
                                                        HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            PaymentResultVO result = depositService.createDepositPayment(userId, orderId, paymentMethod);
            return Result.success("押金支付订单创建成功", result);
        } catch (Exception e) {
            log.error("创建押金支付订单失败：{}", e.getMessage(), e);
            return Result.error("创建押金支付订单失败：" + e.getMessage());
        }
    }

    /**
     * 处理押金退还
     */
    @PostMapping("/refund/{orderId}")
    public Result<DepositRefundResultVO> processDepositRefund(@PathVariable @NotNull(message = "订单ID不能为空") Long orderId,
                                                              @RequestParam BigDecimal feeAmount,
                                                              @RequestParam(required = false) String refundReason,
                                                              HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            DepositRefundResultVO result = depositService.processDepositRefund(userId, orderId, feeAmount, refundReason);
            return Result.success("押金退还处理成功", result);
        } catch (Exception e) {
            log.error("处理押金退还失败：{}", e.getMessage(), e);
            return Result.error("处理押金退还失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户押金记录
     */
    @GetMapping("/records")
    public Result<PageResult<DepositRecordVO>> getUserDepositRecords(@RequestParam(defaultValue = "1") int page,
                                                                     @RequestParam(defaultValue = "10") int size,
                                                                     HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            PageResult<DepositRecordVO> result = depositService.getUserDepositRecords(userId, page, size);
            return Result.success("押金记录查询成功", result);
        } catch (Exception e) {
            log.error("查询押金记录失败：{}", e.getMessage(), e);
            return Result.error("查询押金记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户押金统计信息
     */
    @GetMapping("/summary")
    public Result<DepositSummaryVO> getUserDepositSummary(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            DepositSummaryVO result = depositService.getUserDepositSummary(userId);
            return Result.success("押金统计信息获取成功", result);
        } catch (Exception e) {
            log.error("获取押金统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取押金统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}